package com.iplay.web.totp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iplay.component.mailer.Mailer;
import com.iplay.configuration.mail.MailConfigurationProperties;
import com.iplay.configuration.security.jwtAuthentication.auth.UserContext;
import com.iplay.service.totp.TOTPService;
import com.iplay.service.user.UserService;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/api/totp")
@EnableConfigurationProperties(MailConfigurationProperties.class)
public class TOTPController {
	
	@Autowired
	private TOTPService totpService;
	
	@Autowired
	private UserService userService;

	@Autowired
	private Mailer mailer;

	@Autowired
	private MailConfigurationProperties mailConfigurationProperties;

	@ApiOperation(notes = "身份已认证的用户获得基于时间戳的一次性密码，密码以邮件的方式发送给用户", value = "")
	@GetMapping
	@PreAuthorize("hasAnyRole('USER', 'MANAGER')")
	public boolean generateTOTP(@ApiIgnore @AuthenticationPrincipal UserContext context) {
		String totp =  totpService.generateTOTPUsingDefaultSecretKey();
		userService.findById(context.getUserId()).ifPresent(user -> {
			mailer.sendMail(mailConfigurationProperties.getSender(), user.getEmail(), 
					mailConfigurationProperties.getTotpEmail().getSubject(), mailConfigurationProperties.getTotpEmail().getContent()
					.replace("{totp}", totp));
		});
		System.out.println(totp);
		return true;
	}
}
